<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 函数  函数是组织好的，可重复使用的，用来实现单一，或相关联功能的代码段。 函数能提高应用的模块性，和代码的重复利用率。 定义函数的规则：1). 函数代码块以 def 关键词开头，后接函数标识符名称和圆括号 ()。2). 任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。3). 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。4). 函数内容以冒号起始">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Python-学习(四)">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Python/Python-学习(四)/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 函数  函数是组织好的，可重复使用的，用来实现单一，或相关联功能的代码段。 函数能提高应用的模块性，和代码的重复利用率。 定义函数的规则：1). 函数代码块以 def 关键词开头，后接函数标识符名称和圆括号 ()。2). 任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。3). 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。4). 函数内容以冒号起始">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-b8a190ec6516c3e3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-582310151841270c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-a6f995b16d7a9b34.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-b023d5a02abbee8c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-ee0c5138f88b7b19.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-a176b3ce6f9a738b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-4cd87e1f08115078.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-360b25e7d710918f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-2d396fa90ab8cc64.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-dbef77a4754d98ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-a43469d027d71349.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/3110861-0e824adcfe388f29.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-8b4cad79a6ea4dc7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-dc970e1341c61d05.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-0d9c317cc7ceedd3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-c9d729b4f3fba54b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:32:34.193Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Python-学习(四)">
<meta name="twitter:description" content="####1. 函数  函数是组织好的，可重复使用的，用来实现单一，或相关联功能的代码段。 函数能提高应用的模块性，和代码的重复利用率。 定义函数的规则：1). 函数代码块以 def 关键词开头，后接函数标识符名称和圆括号 ()。2). 任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。3). 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。4). 函数内容以冒号起始">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-b8a190ec6516c3e3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Python/Python-学习(四)/"/>





  <title>Python-学习(四) | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Python/Python-学习(四)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Python-学习(四)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:39+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 函数</p>
<ul>
<li>函数是组织好的，可重复使用的，用来实现单一，或相关联功能的代码段。</li>
<li>函数能提高应用的模块性，和代码的重复利用率。</li>
<li><p>定义函数的规则：<br>1). 函数代码块以 def 关键词开头，后接函数标识符名称和圆括号 ()。<br>2). 任何传入参数和自变量必须放在圆括号中间，圆括号之间可以用于定义参数。<br>3). 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。<br>4). 函数内容以冒号起始，并且缩进。<br>5). return [表达式] 结束函数，选择性地返回一个值给调用方。不带表达式的return相当于返回 None。</p>
<a id="more"></a>
</li>
<li><p>语法：<br>Python 定义函数使用 def 关键字，一般格式如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">def 函数名（参数列表）:</span><br><span class="line">    函数体</span><br></pre></td></tr></table></figure>
<p>默认情况下，参数值和参数名称是按函数声明中定义的的顺序匹配起来的。</p>
</li>
</ul>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># 计算面积函数</span><br><span class="line">def area(width, height):</span><br><span class="line">	return width * height</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">w = 4</span><br><span class="line">h = 5</span><br><span class="line">print (&quot;width = &quot;, w, &quot; height = &quot;, h, &quot; area = &quot;, area(w,h))</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-b8a190ec6516c3e3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>####2. 可更改(mutable)与不可更改(immutable)对象<br>在 python 中，strings, tuples, 和 numbers 是不可更改的对象，而 list,dict 等则是可以修改的对象。</p>
<ul>
<li>不可变类型：变量赋值 a=5 后再赋值 a=10，这里实际是新生成一个 int 值对象 10，再让 a 指向它，而 5 被丢弃，不是改变a的值，相当于新生成了a。<ul>
<li>可变类型：变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改，本身la没有动，只是其内部的一部分值被修改了。</li>
</ul>
</li>
</ul>
<p>####3. 参数</p>
<ul>
<li>必需参数<br>必需参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样</li>
<li>关键字参数<br>关键字参数和函数调用关系紧密，函数调用使用关键字参数来确定传入的参数值。</li>
<li>默认参数<br>调用函数时，如果没有传递参数，则会使用默认参数。</li>
<li>不定长参数<br>基本语法如下：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">def functionname([formal_args,] *var_args_tuple ):</span><br><span class="line">   &quot;函数_文档字符串&quot;</span><br><span class="line">   function_suite</span><br><span class="line">   return [expression]</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>加了星号（*）的变量名会存放所有未命名的变量参数。如果在函数调用时没有指定参数，它就是一个空元组。</p>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># 必需参数</span><br><span class="line">def printStr(str):</span><br><span class="line">	print(str)</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">print(&quot;mazaiting&quot;)</span><br><span class="line"></span><br><span class="line"># 关键字参数</span><br><span class="line">def printMe(str):</span><br><span class="line">	print(str)</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">printMe(str = &quot;zaitingma&quot;)</span><br><span class="line"></span><br><span class="line"># 默认参数</span><br><span class="line">def printInfo(name, age = 24):</span><br><span class="line">	print(&quot;名字：&quot;, name)</span><br><span class="line">	print(&quot;年龄：&quot;, age)</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">printInfo(name = &quot;mazaiting&quot;)</span><br><span class="line"></span><br><span class="line"># 不定长参数</span><br><span class="line">def printInfo(arg, *vartuple):</span><br><span class="line">	print(&quot;输出：&quot;)</span><br><span class="line">	print(arg)</span><br><span class="line">	for var in vartuple:</span><br><span class="line">		print(var)</span><br><span class="line">		pass</span><br><span class="line">	pass</span><br><span class="line">printInfo(70, 60, 50)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-582310151841270c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>####4. 匿名函数</p>
<ul>
<li><p>所谓匿名，意即不再使用 def 语句这样标准的形式定义一个函数。<br>1). lambda 只是一个表达式，函数体比 def 简单很多。<br>2). lambda的主体是一个表达式，而不是一个代码块。仅仅能在lambda表达式中封装有限的逻辑进去。<br>3). lambda 函数拥有自己的命名空间，且不能访问自己参数列表之外或全局命名空间里的参数。<br>4). 虽然lambda函数看起来只能写一行，却不等同于C或C++的内联函数，后者的目的是调用小函数时不占用栈内存从而增加运行效率。</p>
</li>
<li><p>语法<br>lambda 函数的语法只包含一个语句，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">lambda [arg1 [,arg2,.....argn]]:expression</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"># lambda表达式</span><br><span class="line"># 可写函数说明</span><br><span class="line">sum = lambda arg1, arg2: arg1 + arg2</span><br><span class="line"></span><br><span class="line"># 调用sum函数</span><br><span class="line">print(&quot;相加后的值为：&quot;, sum(10, 20))</span><br><span class="line">print(&quot;相加后的值为：&quot;, sum(20, 20))</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-a6f995b16d7a9b34.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>####5. return语句<br>return [表达式] 语句用于退出函数，选择性地向调用方返回一个表达式。不带参数值的return语句返回None<br>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># return 语句</span><br><span class="line">def sum(arg1, arg2):</span><br><span class="line">	total = arg1 + arg2</span><br><span class="line">	return total</span><br><span class="line">	pass</span><br><span class="line"># 调用sum函数</span><br><span class="line">total = sum(10, 20)</span><br><span class="line">print(&quot;函数：&quot;,total)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-b023d5a02abbee8c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>
<p>####6. 变量作用域<br>Python的作用域一共有4种，分别是：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">L （Local） 局部作用域</span><br><span class="line">E （Enclosing） 闭包函数外的函数中</span><br><span class="line">G （Global） 全局作用域</span><br><span class="line">B （Built-in） 内建作用域</span><br></pre></td></tr></table></figure></p>
<p>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"># 内建作用域</span><br><span class="line">x = int(2.9)</span><br><span class="line"># 全局作用域</span><br><span class="line">g_count = 0</span><br><span class="line">def outer():</span><br><span class="line">	# 闭包函数外的函数中</span><br><span class="line">	o_count = 1</span><br><span class="line">	def inner():</span><br><span class="line">		# 局部作用域</span><br><span class="line">		i_count = 2</span><br><span class="line">		pass</span><br><span class="line"> 	pass</span><br></pre></td></tr></table></figure></p>
<p>Python 中只有模块（module），类（class）以及函数（def、lambda）才会引入新的作用域，其它的代码块（如 if/elif/else/、try/except、for/while等）是不会引入新的作用域的，也就是说这些语句内定义的变量，外部也可以访问.<br>当内部作用域想修改外部作用域的变量时，就要用到global和nonlocal关键字:</p>
<ul>
<li><p>global </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">num = 1</span><br><span class="line">def fun1():</span><br><span class="line">    global num  # 需要使用 global 关键字声明</span><br><span class="line">    print(num) </span><br><span class="line">    num = 123</span><br><span class="line">    print(num)</span><br><span class="line">fun1()</span><br></pre></td></tr></table></figure>
</li>
<li><p>nonlocal关键字</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">def outer():</span><br><span class="line">    num = 10</span><br><span class="line">    def inner():</span><br><span class="line">        nonlocal num   # nonlocal关键字声明</span><br><span class="line">        num = 100</span><br><span class="line">        print(num)</span><br><span class="line">    inner()</span><br><span class="line">    print(num)</span><br><span class="line">outer()</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>####7. 模块<br>Python 提供了一个办法，把这些定义存放在文件中，为一些脚本或者交互式的解释器实例使用，这个文件被称为模块。<br>模块是一个包含所有你定义的函数和变量的文件，其后缀名是.py。模块可以被别的程序引入，以使用该模块中的函数等功能。<br>1). 引用标准库<br>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">import sys</span><br><span class="line"></span><br><span class="line">print(&quot;命令行参数如下：&quot;)</span><br><span class="line"></span><br><span class="line">for i in sys.argv:</span><br><span class="line">	print(i)</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">print(&quot;\n\nPython 路径为：&quot;, sys.path, &apos;\n&apos;)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-ee0c5138f88b7b19.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"></p>
<p>2). import 语句<br>想使用 Python 源文件，只需在另一个源文件里执行 import 语句，语法如下：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">import module1[, module2[,... moduleN]</span><br></pre></td></tr></table></figure></p>
<p>当解释器遇到 import 语句，如果模块在当前的搜索路径就会被导入。<br>示例：<br>Support.py文件：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">def print_func(str):</span><br><span class="line">	print(&quot;Hello: &quot;, str)</span><br><span class="line">	return</span><br></pre></td></tr></table></figure></p>
<p>Module.py文件<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># 引入Support.py文件</span><br><span class="line"># 导入模块</span><br><span class="line">import Support</span><br><span class="line"></span><br><span class="line"># 调用Support中的函数</span><br><span class="line">Support.print_func(&quot;Mazaiting&quot;)</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-a176b3ce6f9a738b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-4cd87e1f08115078.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>3). From…import* 语句<br>把一个模块的所有内容全都导入到当前的命名空间也是可行的，只需使用如下声明：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">from modname import *</span><br></pre></td></tr></table></figure></p>
<p>这提供了一个简单的方法来导入一个模块中的所有项目。然而这种声明不该被过多地使用。</p>
<p>4). <strong>name</strong>属性<br>一个模块被另一个程序第一次引入时，其主程序将运行。如果我们想在模块被引入时，模块中的某一程序块不执行，我们可以用<strong>name</strong>属性来使该程序块仅在该模块自身运行时执行。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"># Module.py</span><br><span class="line">if __name__ == &apos;__main__&apos;:</span><br><span class="line">	print(&quot;程序自身在运行&quot;)</span><br><span class="line">else:</span><br><span class="line">	print(&quot;我来自另一模块&quot;)</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-360b25e7d710918f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<p>5). dir() 函数<br>内置的函数 dir() 可以找到模块内定义的所有名称。以一个字符串列表的形式返回:<br>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-2d396fa90ab8cc64.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图9.png"></p>
<p>####8. 包<br>包是一种管理 Python 模块命名空间的形式，采用”点模块名称”。<br>比如一个模块的名称是 A.B， 那么他表示一个包 A中的子模块 B 。<br>就好像使用模块的时候，你不用担心不同模块之间的全局变量相互影响一样，采用点模块名称这种形式也不用担心不同库之间的模块重名的情况。<br>这样不同的作者都可以提供 NumPy 模块，或者是 Python 图形库。<br>不妨假设你想设计一套统一处理声音文件和数据的模块（或者称之为一个”包”）。<br>现存很多种不同的音频文件格式（基本上都是通过后缀名区分的，例如： .wav，:file:.aiff，:file:.au，），所以你需要有一组不断增加的模块，用来在不同的格式之间转换。<br>并且针对这些音频数据，还有很多不同的操作（比如混音，添加回声，增加均衡器功能，创建人造立体声效果），所以你还需要一组怎么也写不完的模块来处理这些操作。<br>这里给出了一种可能的包结构（在分层的文件系统中）:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">sound/                          顶层包</span><br><span class="line">      __init__.py               初始化 sound 包</span><br><span class="line">      formats/                  文件格式转换子包</span><br><span class="line">              __init__.py</span><br><span class="line">              wavread.py</span><br><span class="line">              wavwrite.py</span><br><span class="line">              aiffread.py</span><br><span class="line">              aiffwrite.py</span><br><span class="line">              auread.py</span><br><span class="line">              auwrite.py</span><br><span class="line">              ...</span><br><span class="line">      effects/                  声音效果子包</span><br><span class="line">              __init__.py</span><br><span class="line">              echo.py</span><br><span class="line">              surround.py</span><br><span class="line">              reverse.py</span><br><span class="line">              ...</span><br><span class="line">      filters/                  filters 子包</span><br><span class="line">              __init__.py</span><br><span class="line">              equalizer.py</span><br><span class="line">              vocoder.py</span><br><span class="line">              karaoke.py</span><br><span class="line">              ...</span><br></pre></td></tr></table></figure></p>
<p>####9. 输入输出<br>1). 输出<br>Python两种输出值的方式: 表达式语句和 print() 函数。<br>第三种方式是使用文件对象的 write() 方法，标准输出文件可以用 sys.stdout 引用。<br>如果你希望输出的形式更加多样，可以使用 str.format() 函数来格式化输出值。<br>如果你希望将输出的值转成字符串，可以使用 repr() 或 str() 函数来实现。</p>
<ul>
<li>str()： 函数返回一个用户易读的表达形式</li>
<li>repr()： 产生一个解释器易读的表达形式<br>示例：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># 返回一个用户易读的表达形式</span><br><span class="line">x = str(1/7)</span><br><span class="line">print(x)</span><br><span class="line"># 产生一个解析器易读的表达形式</span><br><span class="line">y = 100 * 100</span><br><span class="line">print(repr(y))</span><br><span class="line"># 格式话</span><br><span class="line">print(&quot;&#123;&#125;网址：&apos;&#123;other&#125;!&apos;&quot;.format(&quot;百度&quot;,other=&quot;www.baidu.com&quot;))</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-dbef77a4754d98ff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图10.png"><br>2). 读键盘输入<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"># 从键盘输入</span><br><span class="line">str = input(&quot;请输入：&quot;)</span><br><span class="line">print(&quot;你输入的内容是：&quot;, str)</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-a43469d027d71349.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图11.png"></p>
<p>3). 读写文件</p>
<ul>
<li>读文件:open() 将会返回一个 file 对象，基本语法格式如下:<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">open(filename, mode)</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>filename：filename 变量是一个包含了你要访问的文件名称的字符串值。<br>mode：mode决定了打开文件的模式：只读，写入，追加等。所有可取值见如下的完全列表。这个参数是非强制的，默认文件访问模式为只读(r)。只读(r), 二进制读(rb),读写(r+),二进制读写(rb+),写(w),二进制写(wb),读写(w+),二进制读写(wb+),追加(a),二进制追加(ab),读写追加(a+),二进制读写追加(ab+).<br><img src="http://upload-images.jianshu.io/upload_images/3110861-0e824adcfe388f29.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图12.png"><br><strong>写入文件</strong>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># 打开文件</span><br><span class="line">file = open(&quot;test.txt&quot;,&quot;w&quot;)</span><br><span class="line"># 定义数据</span><br><span class="line">str = &quot;Python 是一个非常好的语言。&quot;</span><br><span class="line"># 写入文件</span><br><span class="line">file.write(str)</span><br><span class="line"># 关闭打开的文件</span><br><span class="line">file.close</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-8b4cad79a6ea4dc7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图13.png"></p>
<p><strong>读取文件</strong>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"># 读取文件</span><br><span class="line">file = open(&quot;test.txt&quot;, &quot;r&quot;)</span><br><span class="line"># 读取数据</span><br><span class="line">str = file.read()</span><br><span class="line"># 打印</span><br><span class="line">print(str)</span><br><span class="line"># 关闭打开文件</span><br><span class="line">file.close()</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-dc970e1341c61d05.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图14.png"></p>
<ul>
<li>readline():  会从文件中读取单独的一行。换行符为 ‘\n’。f.readline() 如果返回一个空字符串, 说明已经已经读取到最后一行。</li>
<li>readlines(): 将返回该文件中包含的所有行。如果设置可选参数 sizehint, 则读取指定长度的字节, 并且将这些字节按行分割。</li>
<li>write(string)：将 string 写入到文件中, 然后返回写入的字符数。</li>
<li>tell()：返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数。</li>
<li><p>seek()：如果要改变文件当前的位置, 可以使用 f.seek(offset, from_what) 函数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">from_what 的值, 如果是 0 表示开头, 如果是 1 表示当前位置, 2 表示文件的结尾，例如：</span><br><span class="line"></span><br><span class="line">seek(x,0) ： 从起始位置即文件首行首字符开始移动 x 个字符</span><br><span class="line">seek(x,1) ： 表示从当前位置往后移动x个字符</span><br><span class="line">seek(-x,2)：表示从文件的结尾往前移动x个字符</span><br><span class="line">from_what 值为默认为0，即文件开头。</span><br></pre></td></tr></table></figure>
</li>
<li><p>close(): 在文本文件中 (那些打开文件的模式下没有 b 的), 只会相对于文件起始位置进行定位。你处理完一个文件后, 调用 f.close() 来关闭文件并释放系统的资源，如果尝试再调用该文件，则会抛出异常。</p>
</li>
</ul>
<p>4). pickle 模块<br>python的pickle模块实现了基本的数据序列和反序列化。通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去，永久存储。通过pickle模块的反序列化操作，我们能够从文件中创建上一次程序保存的对象。<br>基本接口：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pickle.dump(obj, file, [,protocol])</span><br></pre></td></tr></table></figure></p>
<p>有了 pickle 这个对象, 就能对 file 以读取的形式打开:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">x = pickle.load(file)</span><br></pre></td></tr></table></figure></p>
<p><strong>注：从 file 中读取一个字符串，并将它重构为原来的python对象。</strong><br><strong>存入数据</strong>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"># 导入pickle</span><br><span class="line">import pickle</span><br><span class="line"># 使用pickle模块将数据对象保存到文件</span><br><span class="line">data = &#123;</span><br><span class="line">	&apos;a&apos;:[1,2.3,4,5+6j],</span><br><span class="line">	&apos;b&apos;:(&apos;string&apos;, u&apos;Unicode string&apos;),</span><br><span class="line">	&apos;c&apos;:None</span><br><span class="line">&#125;</span><br><span class="line"># 打开文件</span><br><span class="line">output = open(&apos;data.pkl&apos;, &apos;wb&apos;)</span><br><span class="line"># 写入数据</span><br><span class="line">pickle.dump(data, output)</span><br><span class="line"># 关闭文件</span><br><span class="line">output.close()</span><br></pre></td></tr></table></figure></p>
<p><strong>写入数据</strong>示例：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"># 导入pickle</span><br><span class="line">import pprint,pickle</span><br><span class="line"># 使用pickle模块从文件中重构python对象</span><br><span class="line">file = open(&apos;data.pkl&apos;,&apos;rb&apos;)</span><br><span class="line"># 重构对象</span><br><span class="line">data = pickle.load(file)</span><br><span class="line"># 打印数据</span><br><span class="line">pprint.pprint(data)</span><br><span class="line"># 关闭文件</span><br><span class="line">file.close()</span><br></pre></td></tr></table></figure></p>
<p>执行结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-0d9c317cc7ceedd3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图15.png"></p>
<p>####10. 遍历文件夹<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">import os</span><br><span class="line">import os.path</span><br><span class="line"># 获取指定目录及其子目录下的py文件</span><br><span class="line">l = []</span><br><span class="line">def get_py(path, list):</span><br><span class="line">	# 获取path目录下的所有文件</span><br><span class="line">	fileList = os.listdir(path)</span><br><span class="line">	for fileName in fileList:</span><br><span class="line">		# 获取path与fileName组合后的路径</span><br><span class="line">		pathTmp = os.path.join(path, fileName)</span><br><span class="line">		# 如果是目录</span><br><span class="line">		if os.path.isdir(pathTmp):</span><br><span class="line">			# 递归查找</span><br><span class="line">			get_py(pathTmp, list)</span><br><span class="line">			pass</span><br><span class="line">			# 不是目录，则比较后缀名</span><br><span class="line">		elif fileName[-3:].upper()==&apos;.PY&apos;:</span><br><span class="line">			list.append(pathTmp)</span><br><span class="line">			pass</span><br><span class="line">		pass</span><br><span class="line">	pass</span><br><span class="line"></span><br><span class="line">path = input(&quot;请输入路径: &quot;).strip()</span><br><span class="line"></span><br><span class="line">get_py(path, l)</span><br><span class="line"></span><br><span class="line">print(&quot;在%s目录及其子目录下找到%d个py文件\n分别为：&quot;%(path,len(l)))</span><br><span class="line"></span><br><span class="line">for filePath in l:</span><br><span class="line">	print(filePath+&apos;\n&apos;)</span><br><span class="line">	pass</span><br></pre></td></tr></table></figure></p>
<p>打印结果：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-c9d729b4f3fba54b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图16.png"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-学习(十)--数据解析/" rel="next" title="Python-学习(十)--数据解析">
                <i class="fa fa-chevron-left"></i> Python-学习(十)--数据解析
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Python/Python-环境搭建(Windows)/" rel="prev" title="Python-环境搭建(Windows)">
                Python-环境搭建(Windows) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
